package com.iterator.service.wechat.order;

import com.github.pagehelper.PageHelper;
import com.iterator.bean.web.pojo.OrderGoods;
import com.iterator.bean.web.pojo.lyh.MallAddress;
import com.iterator.bean.web.pojo.lyh.MallUserExample;
import com.iterator.bean.web.pojo.lyh.User;
import com.iterator.bean.web.pojo.tcy.Comment;
import com.iterator.bean.web.pojo.zql.Coupon;
import com.iterator.bean.wechat.order.bo.CommentOrderBO;
import com.iterator.bean.wechat.order.bo.SubmitOrderBO;
import com.iterator.bean.wechat.order.pojo.WxOrder;
import com.iterator.bean.wechat.order.pojo.WxOrderExample;
import com.iterator.bean.wechat.order.pojo.WxOrderGoods;
import com.iterator.bean.wechat.order.pojo.WxOrderGoodsExample;
import com.iterator.bean.wechat.order.vo.*;
import com.iterator.bean.wechat.tcy.pojo.MyCart;
import com.iterator.bean.wechat.tcy.pojo.MyCartExample;
import com.iterator.bean.wechat.wy.address.AddressBO;
import com.iterator.bean.wechat.wy.address.AddressDetailVO;
import com.iterator.mapper.web.goodsManager.CommentMapper;
import com.iterator.mapper.web.promotionMapper.CouponMapper;
import com.iterator.mapper.web.userManager.MallUserMapper;
import com.iterator.mapper.wechat.lyh.WxUserMapper;
import com.iterator.mapper.wechat.order.AddressWxMapper;
import com.iterator.mapper.wechat.order.SystemMapper;
import com.iterator.mapper.wechat.order.WxOrderGoodsMapper;
import com.iterator.mapper.wechat.order.WxOrderMapper;
import com.iterator.mapper.wechat.tcy.MyCartMapper;
import com.iterator.mapper.wechat.wy.address.WxAddressMapper;
import net.sf.jsqlparser.statement.Commit;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author : L
 * @ProjectName : project-2
 * @Date : 1/12/2021
 * @Description :
 */
@Service
public class WxOrderServiceImpl implements WxOrderService {
    @Autowired
    WxOrderMapper wxOrderMapper;
    @Autowired
    WxOrderGoodsMapper wxOrderGoodsMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    AddressWxMapper addressWxMapper;
    @Autowired
    MallUserMapper mallUserMapper;
    @Autowired
    SystemMapper systemMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    MyCartMapper myCartMapper;
    @Autowired
    WxUserMapper wxUserMapper;

    @Override
    public List<OrderListDataVO> queryOrderListByShowType (Integer showType, Integer page, Integer size){
        PageHelper.startPage(page, size);

        WxOrderExample wxOrderExample = new WxOrderExample();

        wxOrderExample.setOrderByClause("update_time desc");

        Subject subject = SecurityUtils.getSubject();
        String name = (String) subject.getPrincipal();
        User user = mallUserMapper.selectUserByName(name);
        Integer userId = user.getId();

        WxOrderExample.Criteria criteria = wxOrderExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);

        if (showType == null) {
            showType = 0;
        }
        if (showType == 0) {
            // 全部
            criteria.andOrderStatusBetween((short) 101, (short) 402);
        }
        if (showType == 1) {
            // 待付款（未付款）
            criteria.andOrderStatusEqualTo((short) 101);
        }
        if (showType == 2) {
            // 待发货（已付款）
            criteria.andOrderStatusEqualTo((short) 201);
        }
        if (showType == 3) {
            // 待收货（已发货）
            criteria.andOrderStatusEqualTo((short) 301);
        }
        if (showType == 4) {
            // 待评价（401用户收货，402系统收货）
            criteria.andOrderStatusGreaterThanOrEqualTo((short) 401);
        }

        // 根据订单状态查询到的相应订单列表
        List<WxOrder> wxOrders = wxOrderMapper.selectByExample(wxOrderExample);

        // 封装订单列表数据到 orderListDataVOS
        List<OrderListDataVO> orderListDataVOS = new ArrayList<>();
        for (WxOrder wxOrder : wxOrders) {
            OrderListDataVO orderListDataVO = new OrderListDataVO();
            // 根据订单状态码得到订单状态描述
            orderListDataVO.setOrderStatusText(wxOrder.getOrderStatus());
            // 判断是否团购订单
            if (wxOrder.getGrouponPrice() != null) {
                orderListDataVO.setIsGroupin(true);
            } else {
                orderListDataVO.setIsGroupin(false);
            }
            orderListDataVO.setOrderSn(wxOrder.getOrderSn());
            orderListDataVO.setActualPrice(wxOrder.getActualPrice());
            orderListDataVO.setId(wxOrder.getId());
            orderListDataVO.setHandleOption(wxOrder.getOrderStatus());

            // List<GoodsListBeanVO> goodslist
            // 根据订单id，查询某一订单中的商品
            WxOrderGoodsExample orderGoodsExample = new WxOrderGoodsExample();
            WxOrderGoodsExample.Criteria criteria1 = orderGoodsExample.createCriteria();
            criteria1.andOrderIdEqualTo(wxOrder.getId());
            List<WxOrderGoods> wxOrderGoods = wxOrderGoodsMapper.selectByExample(orderGoodsExample);

            ArrayList<GoodsListBeanVO> goodsListBeanVOS = new ArrayList<>();
            // 遍历订单中的商品，封装进 goodsListBeanVOS
            for (WxOrderGoods wxOrderGood : wxOrderGoods) {
                GoodsListBeanVO goodsListBeanVO = new GoodsListBeanVO();

                goodsListBeanVO.setNumber(wxOrderGood.getNumber());
                goodsListBeanVO.setPicUrl(wxOrderGood.getPicUrl());
                goodsListBeanVO.setId(wxOrderGood.getId());
                goodsListBeanVO.setGoodsName(wxOrderGood.getGoodsName());
                goodsListBeanVOS.add(goodsListBeanVO);
            }
            orderListDataVO.setGoodsList(goodsListBeanVOS);

            orderListDataVOS.add(orderListDataVO);
        }
        return orderListDataVOS;
    }

    @Override
    public WxOrderDetailVO queryOrderDetailById (Integer orderId){
        // 通过 orderId 查询 order_goods 表
        WxOrderGoodsExample wxOrderGoodsExample = new WxOrderGoodsExample();
        WxOrderGoodsExample.Criteria criteria = wxOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<WxOrderGoods> wxOrderGoods = wxOrderGoodsMapper.selectByExample(wxOrderGoodsExample);

        // 查询 order 表获取订单信息
        ArrayList<OrderInfoBeanVO> orderInfoBeanVOS = new ArrayList<>();
        WxOrder wxOrder = wxOrderMapper.selectByPrimaryKey(orderId);

        OrderInfoBeanVO orderInfoBeanVO = new OrderInfoBeanVO();
        orderInfoBeanVO.setConsignee(wxOrder.getConsignee());
        orderInfoBeanVO.setAddress(wxOrder.getAddress());
        orderInfoBeanVO.setAddTime(wxOrder.getAddTime());
        orderInfoBeanVO.setOrderSn(wxOrder.getOrderSn());
        orderInfoBeanVO.setActualPrice(wxOrder.getActualPrice());
        orderInfoBeanVO.setMobile(wxOrder.getMobile());
        orderInfoBeanVO.setOrderStatusText(wxOrder.getOrderStatus());
        orderInfoBeanVO.setGoodsPrice(wxOrder.getGoodsPrice());
        orderInfoBeanVO.setCouponPrice(wxOrder.getCouponPrice());
        orderInfoBeanVO.setId(wxOrder.getId());
        orderInfoBeanVO.setFreightPrice(wxOrder.getFreightPrice());
        orderInfoBeanVO.setHandleOption(wxOrder.getOrderStatus());

        // 封装 wxOrderDetailVO
        WxOrderDetailVO wxOrderDetailVO = new WxOrderDetailVO();
        wxOrderDetailVO.setOrderInfo(orderInfoBeanVO);
        wxOrderDetailVO.setOrderGoods(wxOrderGoods);

        return wxOrderDetailVO;
    }

    @Override
    public Integer cancelOrderById (Integer orderId){
        WxOrder wxOrder = new WxOrder();

        // 订单状态修改为 102
        wxOrder.setOrderStatus((short) 102);
        wxOrder.setUpdateTime(new Date());

        WxOrderExample wxOrderExample = new WxOrderExample();
        WxOrderExample.Criteria criteria = wxOrderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        int i = wxOrderMapper.updateByExampleSelective(wxOrder, wxOrderExample);
        return i;
    }

    @Override
    public Integer refundOrderById (Integer orderId){
        WxOrder wxOrder = new WxOrder();
        wxOrder.setId(orderId);
        wxOrder.setOrderStatus((short) 202);
        wxOrder.setUpdateTime(new Date());
        int i = wxOrderMapper.updateByPrimaryKeySelective(wxOrder);
        return i;
    }

    @Override
    public Integer deleteOrderById (Integer orderId){
        WxOrder wxOrder = new WxOrder();

        wxOrder.setDeleted(true);
        wxOrder.setUpdateTime(new Date());

        WxOrderExample wxOrderExample = new WxOrderExample();
        WxOrderExample.Criteria criteria = wxOrderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        int i = wxOrderMapper.updateByExampleSelective(wxOrder, wxOrderExample);
        return i;
    }

    @Override
    public Integer prepayOrderById (Integer orderId){
        // TODO 支付功能本阶段不做，假设成功下单，更改订单状态
        WxOrder wxOrder = new WxOrder();
        wxOrder.setUpdateTime(new Date());
        wxOrder.setOrderStatus((short) 201);

        WxOrderExample wxOrderExample = new WxOrderExample();
        WxOrderExample.Criteria criteria = wxOrderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        int i = wxOrderMapper.updateByExampleSelective(wxOrder, wxOrderExample);
        return i;
    }

    @Override
    public Integer confirmOrderById (Integer orderId){
        WxOrder wxOrder = new WxOrder();
        wxOrder.setOrderStatus((short) 401);
        wxOrder.setUpdateTime(new Date());
        wxOrder.setConfirmTime(new Date());

        WxOrderExample wxOrderExample = new WxOrderExample();
        WxOrderExample.Criteria criteria = wxOrderExample.createCriteria();
        criteria.andIdEqualTo(orderId);
        int i = wxOrderMapper.updateByExampleSelective(wxOrder, wxOrderExample);
        return i;
    }

    @Override
    public List<WxOrderGoods> queryOrderGoods (Integer orderId, Integer goodsId){
        WxOrderGoodsExample wxOrderGoodsExample = new WxOrderGoodsExample();
        WxOrderGoodsExample.Criteria criteria = wxOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andGoodsIdEqualTo(goodsId);
        criteria.andDeletedEqualTo(false);

        List<WxOrderGoods> wxOrderGoods = wxOrderGoodsMapper.selectByExample(wxOrderGoodsExample);
        return wxOrderGoods;
    }

    @Override
    public Integer commentOrder (CommentOrderBO commentOrderBO){
        Comment comment = new Comment();

        String username = (String) SecurityUtils.getSubject().getPrincipal();
        Integer userId = wxUserMapper.selectUserIdByName(username);

        WxOrderGoods orderGoods = wxOrderGoodsMapper.selectByPrimaryKey(commentOrderBO.getOrderGoodsId());

        comment.setUserId(userId);
        // type == 0, 商品评论
        comment.setType(0);
        comment.setValueId(commentOrderBO.getOrderGoodsId());
        comment.setContent(commentOrderBO.getContent());
        comment.setStar(commentOrderBO.getStar());
        comment.setHasPicture(commentOrderBO.isHasPicture());
        comment.setPicUrls(commentOrderBO.getPicUrls());
        comment.setAddTime(new Date());
        comment.setDeleted(false);

        int i = commentMapper.insertSelective(comment);
        orderGoods.setComment(comment.getId());
        orderGoods.setUpdateTime(comment.getAddTime());
        wxOrderGoodsMapper.updateByPrimaryKey(orderGoods);

        return i;
    }

    @Override
    public Integer createOrder(SubmitOrderBO submitOrderBO, AddressDetailVO address) {
        WxOrder wxOrder = new WxOrder();

        String username = (String) SecurityUtils.getSubject().getPrincipal();
        Integer userId = wxUserMapper.selectUserIdByName(username);

        WxOrder wxOrder1 = GetWxOrder(submitOrderBO, address, wxOrder);
        int i = wxOrderMapper.insertSelective(wxOrder1);

        Integer orderId = wxOrder1.getId();


        MyCartExample myCartExample = new MyCartExample();
        MyCartExample.Criteria criteria = myCartExample.createCriteria();

        if(submitOrderBO.getCartId() == 0){
            // 直接在购物车中下单
            criteria.andDeletedEqualTo(true);
            criteria.andUserIdEqualTo(userId);
            criteria.andCheckedEqualTo(true);

        }else{
            // 立即购买
            criteria.andIdEqualTo(submitOrderBO.getCartId());
            criteria.andDeletedEqualTo(true);
        }

        List<MyCart> carts = myCartMapper.selectByExample(myCartExample);

        if(submitOrderBO.getCartId() == 0){
            //查完之后修改购物车的状态
            for (MyCart cart : carts) {
                MyCart updateCartDeleted = new MyCart();
                updateCartDeleted.setDeleted(false);
                updateCartDeleted.setUpdateTime(new Date());

                MyCartExample cartE = new MyCartExample();
                MyCartExample.Criteria cartCriteria = cartE.createCriteria();

                criteria.andDeletedEqualTo(true);
                criteria.andUserIdEqualTo(userId);
                criteria.andCheckedEqualTo(true);

                myCartMapper.updateByExampleSelective(updateCartDeleted,cartE);
            }
        }
        // 订单编号
        wxOrder1.setOrderSn(addOrderSn());

        wxOrder1.setOrderStatus((short) 101);

        // 收货人信息
        wxOrder1.setConsignee(address.getName());
        wxOrder1.setMobile(address.getMobile());
        wxOrder1.setAddress(address.getAddress());

        // 商品价格
        // wxOrder.setGoodsPrice();
        ArrayList<WxOrderGoods> wxOrderGoods = new ArrayList<>();
        double sumPrice =0;
        for (MyCart cart : carts) {
            // 封装order_goods
            WxOrderGoods orderGood = new WxOrderGoods();

            orderGood.setOrderId(orderId);
            orderGood.setGoodsId(cart.getGoodsId());
            orderGood.setGoodsSn(cart.getGoodsSn());
            orderGood.setGoodsName(cart.getGoodsName());
            orderGood.setProductId(cart.getProductId());
            orderGood.setPrice(cart.getPrice());
            orderGood.setNumber(cart.getNumber());
            orderGood.setSpecifications(cart.getSpecifications());
            orderGood.setPicUrl(cart.getPicUrl());
            orderGood.setComment(0);
            orderGood.setAddTime(new Date());
            orderGood.setUpdateTime(new Date());
            orderGood.setDeleted(false);

            sumPrice = sumPrice + (cart.getPrice().doubleValue()) *cart.getNumber();
            wxOrderGoods.add(orderGood);
        }
        BigDecimal goodsPrice = new BigDecimal(sumPrice);
        wxOrder1.setGoodsPrice(goodsPrice);

        // 运费
        String min = "cskaoyan_mall_express_freight_min";
        String value = "cskaoyan_mall_express_freight_value";
        String minStr = systemMapper.selectKeyValueByKeyName(min);
        Double minPrice = Double.valueOf(minStr);
        String valueStr = systemMapper.selectKeyValueByKeyName(value);
        Double valuePrice = Double.valueOf(valueStr);

        Double freightPrice = 0.0;
        int i1 = goodsPrice.intValue();
        if (i1 >= minPrice) {
            freightPrice = 0.0;
        } else {
            freightPrice = valuePrice;
        }
        BigDecimal freightPrice1 = new BigDecimal(freightPrice);
        wxOrder1.setFreightPrice(freightPrice1);

        // 优惠券减免价格
        if(submitOrderBO.getCouponId()!=null && submitOrderBO.getCouponId()>0 ){
            BigDecimal couponPrice = couponMapper.selectDiscountByCouponId(submitOrderBO.getCouponId());
            wxOrder1.setCouponPrice(couponPrice);
            // 更改优惠券状态
            Integer total =  couponMapper.selectCouponTotalById(submitOrderBO.getCouponId()) - 1 ;
            Coupon coupon = new Coupon();
            coupon.setId(submitOrderBO.getCouponId());
            coupon.setTotal(total);
            coupon.setUpdateTime(new Date());
            couponMapper.updateByPrimaryKeySelective(coupon);
        }

        // 用户积分减免
        BigDecimal integralPrice = new BigDecimal(1);
        wxOrder.setIntegralPrice(integralPrice);

        // 团购优惠价减免
        BigDecimal groupOnPrice = new BigDecimal(0);
        wxOrder.setGrouponPrice(groupOnPrice);

        // 订单费用 = goods_price + freight_price - coupon_price
        BigDecimal orderPrice = goodsPrice.add(freightPrice1).subtract(wxOrder1.getCouponPrice());
        wxOrder.setOrderPrice(orderPrice);

        // 实付费用 = order_price - integral_price
        BigDecimal actualPrice = orderPrice.subtract(integralPrice);
        wxOrder.setActualPrice(actualPrice);

        wxOrder.setAddTime(new Date());
        wxOrder.setUpdateTime(new Date());
        wxOrder.setDeleted(false);

        WxOrderExample wxOrderExample = new WxOrderExample();
        WxOrderExample.Criteria criteria1 = wxOrderExample.createCriteria();
        criteria1.andIdEqualTo(wxOrder1.getId());
        wxOrderMapper.updateByExampleSelective(wxOrder1, wxOrderExample);
        for (WxOrderGoods wxOrderGood : wxOrderGoods) {
            wxOrderGoodsMapper.insertSelective(wxOrderGood);
        }
        return wxOrder1.getId();
    }

    private WxOrder GetWxOrder(SubmitOrderBO submitOrderBO, AddressDetailVO addressDetailVO, WxOrder wxOrder) {

        wxOrder.setAddress(addressDetailVO.getProvinceName()+
                addressDetailVO.getCityName()+addressDetailVO.getAreaName()+addressDetailVO.getAddress());

        wxOrder.setOrderSn(addOrderSn());

        //获取user_id
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        Integer userId = wxUserMapper.selectUserIdByName(username);
        wxOrder.setUserId(userId);

        // 确定订单状态：101未付款
        wxOrder.setOrderStatus((short)101);

        //用户名
        wxOrder.setConsignee(addressDetailVO.getName());

        //手机
        wxOrder.setMobile(addressDetailVO.getMobile());

        //留言
        wxOrder.setMessage(submitOrderBO.getMessage());

        wxOrder.setActualPrice(new BigDecimal(0));
        wxOrder.setOrderPrice(new BigDecimal(0));
        wxOrder.setCouponPrice(new BigDecimal(0));
        wxOrder.setFreightPrice(new BigDecimal(0));
        wxOrder.setGoodsPrice(new BigDecimal(0));
        wxOrder.setIntegralPrice(new BigDecimal(0));
        wxOrder.setGrouponPrice(new BigDecimal(0));
        return wxOrder;
    }

    private String addOrderSn() {
        Long timeStamp = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String newOrderSnPre = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));
        Random random = new Random();
        int i = random.nextInt(999999);
        Integer integer = new Integer(i);
        String newOrderSnPost = integer.toString();
        String newOrderSn = newOrderSnPre + newOrderSnPost;
        return newOrderSn;
    }

}

